<?php


namespace addons\facrm\library\notice\queue;

use app\admin\model\Admin;
use app\common\library\Email;
use think\Log;
use think\Queue;
use think\queue\job;
use think\Validate;

/**
 * 合同审批相关通知队列
 * Class FlowContractJob
 * @package addons\facrm\library\notice\queue
 */
class FlowContractJob
{
    public function fire(Job $job, $data)
    {
        if ($job->attempts() > 3) {
            //通过这个方法可以检查这个任务已经重试了几次了
            $this->jobdelete($job);
        }
        //获取对象内容
        $model_info = null;
        if (isset($data['model_id']) && $data['model_id']) {
            $model_info = model('\app\admin\model\facrm\Contract')->find($data['model_id']);
        }
        if (!$model_info) {
            $this->jobdelete($job);
        }
        $model_info = $model_info->toArray();

        if (isset($data['data']['check_status']) && $data['data']['check_status'] == 2) {
            //审核通过通知 通知签约人
            $key = "notice_pass_contract";
            $data['admin_ids'] = $model_info['order_admin_id'];
        } elseif (isset($data['data']['check_status']) && $data['data']['check_status'] == 3) {
            //驳回通知
            $key = "notice_nopass_contract";
            $data['admin_ids'] = $model_info['order_admin_id'];
        } else {
            $key = "notice_flow_contract";
            //不存在就从对象中获取
            $data['admin_ids'] = (isset($data['data']['flow_admin_id']) && $data['data']['flow_admin_id']) ?
                $data['data']['flow_admin_id'] : $model_info['flow_admin_id'];
        }


        $notice_types = \addons\facrm\library\notice\Notice::getProviders();
        $keys = "";
        foreach ($notice_types as $v) {
            $keys .= $keys ? ',' . $key . $v : $key . $v;
        }

        $settingModel = new \app\admin\model\facrm\Setting();
        $setinglist = $settingModel->where('key', 'in', $keys)->where('status', 1)->select();

        if (!$setinglist) {
            $this->jobdelete($job);
        }


        foreach ($setinglist as $r) {
            if (!$r->values['engine']) continue;
            $notice_app = new \addons\facrm\library\notice\Notice(['key' => $r->values['engine']]);
            $notice_app->send($r, $data, $model_info);
        }
        $job->delete();
        return true;


    }

    protected function jobdelete($job)
    {
        $job->delete();
        return false;
    }

    public function failed($data)
    {
        Log::write("流程跟进任务失败：" . print_r(['data' => $data,], true), 'error');
    }
}